﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Menu
{
    public class DelMenuHandler : IRequestHandler<DelMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public DelMenuHandler(IBaseRepository<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var list = menuRepo.GetAll().ToList();
            var count =await Del(request.Id, list);
            if (count>0)
            {
                res.Msg = "删除成功";
                res.Code = ApiEnum.Success;
            }
            else
            {
                res.Msg = "删除失败";
                res.Code = ApiEnum.Fail;
            }
            res.Data = count;
            return await Task.FromResult(res);
        }

        public async Task<int> Del(int Id, List<MenuModel> ids)
        {
            int count = 0;
            var res1 = ids.FirstOrDefault(x => x.Id == Id);
            if (res1!=null && !res1.IsDelete)
            {
                res1.IsDelete = true;
                menuRepo.Update(res1);
                count++;
                var ab = ids.Where(x => x.Pid == Id && !x.IsDelete).ToList();
                foreach (var item in ab)
                {
                    count += await Del(item.Id, ids);
                }
            }
            return count;

        }
    }
}
